package com.wang.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.constant.ErrorCode;
import com.wang.exception.BusinessException;
import com.wang.param.PostCollectionQueryParam;
import com.wang.param.PostQueryParam;
import com.wang.param.PostReviewParam;
import com.wang.param.PostSubmitParam;
import com.wang.reponse.PostVo;
import com.wang.reponse.ShopVo;
import com.wang.reponse.UpvoteVo;
import com.wang.reponse.UserVo;
import com.wang.user.model.*;
import com.wang.user.service.PostCollectionService;
import com.wang.user.service.PostService;
import com.wang.user.mapper.PostMapper;
import com.wang.user.service.ShopService;
import com.wang.user.service.UpvoteService;
import com.wang.user.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author bkty0
* @description 针对表【post(帖子)】的数据库操作Service实现
* @createDate 2025-04-23 10:39:21
*/
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
    implements PostService{

    @Resource
    private PostMapper postMapper;

    @Resource
    private UserService userService;

    @Resource
    private ShopService shopService;

    @Resource
    private UpvoteService upvoteService;

    @Resource
    private PostCollectionService postCollectionService;

    public static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public List<PostVo> listVoByPostIds(List<Long> postIds) {
        if (ObjectUtil.isEmpty(postIds)) {
            return Collections.emptyList();
        }
        List<Post> posts = listByIds(postIds);
        return getPostVoList(posts);
    }

    @Override
    public List<PostVo> listByShopId(PostCollectionQueryParam queryParam) {
        if(ObjectUtil.isNull(queryParam) || ObjectUtil.isNull(queryParam.getShopId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Post::getShopId, queryParam.getShopId());
        queryWrapper.eq(Post::getStatus, 1);
        queryWrapper.orderByDesc(Post::getCreateTime);
        List<Post> postList = list(queryWrapper);
        List<PostVo> postVoList = getPostVoList(postList);
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 1){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount).reversed());
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 2){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount));
        }
        return postVoList;
    }

    public List<PostVo> getPostVoList(List<Post> postList) {
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }
        List<Integer> userIds = postList.stream().map(Post::getUserId).distinct().collect(Collectors.toList());
        List<User> userList = userService.listByIds(userIds);
        Map<Integer, User> userMap = new HashMap<>();
        if(CollUtil.isNotEmpty(userList)){
            userMap = userList.stream().collect(Collectors.toMap(User::getUid, Function.identity()));
        }
        List<Long> postIds = postList.stream().map(Post::getId).distinct().collect(Collectors.toList());
        // 帖子点赞量
        List<UpvoteVo> upvoteVos = upvoteService.postUpvoteCountByPostIds(postIds);
        Map<Long, Long> upvoteMap = new HashMap<>();
        if(CollUtil.isNotEmpty(upvoteVos)){
            upvoteMap = upvoteVos.stream().collect(Collectors.toMap(UpvoteVo::getPostId, UpvoteVo::getUpvoteCount));
        }

        Map<Integer, User> finalUserMap = userMap;
        Map<Long, Long> finalUpvoteMap = upvoteMap;
        return postList.stream().map(post -> {
            PostVo postVo = new PostVo();
            BeanUtils.copyProperties(post, postVo);
            User user = finalUserMap.get(post.getUserId());
            if(ObjectUtil.isNull(user)){
                postVo.setUser(null);
            }else {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                postVo.setUser(userVo);
            }

            ShopVo shopById = shopService.getShopById2(post.getShopId());
            postVo.setShop(shopById);

            //关键字
            String keywords = post.getKeywords();
            if(ObjectUtil.isNotEmpty(keywords)){
                try {
                    List<String> keywordList = objectMapper.readValue(keywords, new TypeReference<List<String>>() {
                    });
                    postVo.setKeywordList(keywordList);
                } catch (JsonProcessingException e) {
                    throw new BusinessException("帖子关键字信息解析错误，帖子id：" + post.getId());
                }
            }
            //点赞量
            Long upvoteCount = finalUpvoteMap.get(post.getId());
            postVo.setUpvoteCount(ObjectUtil.isNotNull(upvoteCount) ? upvoteCount : 0);
            return postVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<PostVo> list(PostCollectionQueryParam queryParam) {
        List<Post> postList = postMapper.list(queryParam);
        postList = postList.stream().filter(item -> item.getStatus() == 1).collect(Collectors.toList());
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }

        List<PostVo> postVoList = getPostVoList(postList);

        // 根据点赞量进行排序
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 1){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount).reversed());
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 2){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount));
        }

        return postVoList;
    }

    /**
     * 发布帖子
     * @param submitParam
     * @return
     */
    @Override
    public Boolean submit(PostSubmitParam submitParam) {
        Post post = new Post();
        BeanUtils.copyProperties(submitParam, post);
        // 新发的贴都需要审核
        post.setStatus(0);

        //关键字
        List<String> keywordList = submitParam.getKeywordList();
        if(CollUtil.isNotEmpty(keywordList)){
            String jsonStr = JSONUtil.toJsonStr(keywordList);
            post.setKeywords(jsonStr);
        }else {
            post.setKeywords(null);
        }
        return save(post);
    }

    /**
     * 审核帖子
     * @param reviewParam
     * @return
     */
    @Override
    public Boolean review(PostReviewParam reviewParam) {
        if(ObjectUtil.isNull(reviewParam) || ObjectUtil.isNull(reviewParam.getPostId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(!Arrays.asList(1,2).contains(reviewParam.getStatus())){
            throw new BusinessException("审核状态参数错误");
        }
        Post post = getById(reviewParam.getPostId());
        if(ObjectUtil.isNull(post)){
            throw new BusinessException("帖子数据不存在");
        }
        post.setStatus(reviewParam.getStatus());
        return updateById(post);
    }

    @Override
    public List<PostVo> adminList(PostCollectionQueryParam queryParam) {
        List<Post> postList = postMapper.list(queryParam);
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }

        List<PostVo> postVoList = getPostVoList(postList);

        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 1){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount).reversed());
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 2){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount));
        }
        return postVoList;
    }

    @Override
    public List<PostVo> myList(PostCollectionQueryParam queryParam) {
        User loginUser = userService.getLoginUser();
        queryParam.setUserId(loginUser.getUid());
        List<Post> postList = postMapper.myList(queryParam);
        postList = postList.stream().filter(item -> item.getStatus() == 1).collect(Collectors.toList());
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }

        List<PostVo> postVoList = getPostVoList(postList);
        // 是否被点赞和收藏
        postVoList = postVoList.stream().peek(item -> {
            Upvote upvote = upvoteService.getByPostIdAndUserId(item.getId(), loginUser.getUid());
            PostCollection postCollection = postCollectionService.getByPostIdAndUserId(item.getId(), loginUser.getUid());
            item.setIsCollected(ObjectUtil.isNotNull(postCollection));
            item.setIsUpvoted(ObjectUtil.isNotNull(upvote));
        }).collect(Collectors.toList());

        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 1){
            postVoList.sort(Comparator.comparingLong(PostVo::getUpvoteCount));
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 2){
            postVoList.sort(Comparator.comparingLong(PostVo::getUpvoteCount).reversed());
        }
        return postVoList;
    }

    @Override
    public List<PostVo> reviewList(PostCollectionQueryParam queryParam) {
        List<Post> postList = postMapper.list(queryParam);
        postList = postList.stream().filter(item -> item.getStatus() == 0).collect(Collectors.toList());
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }

        List<PostVo> postVoList = getPostVoList(postList);
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 1){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount).reversed());
        }
        if(ObjectUtil.isNotNull(queryParam.getSort()) && queryParam.getSort() == 2){
            Collections.sort(postVoList, Comparator.comparingLong(PostVo::getUpvoteCount));
        }
        return postVoList;
    }

    @Override
    public List<PostVo> listByShopId2(Long shopId) {
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Post::getShopId, shopId);
        queryWrapper.eq(Post::getStatus, 1);
        queryWrapper.orderByDesc(Post::getCreateTime);
        List<Post> postList = list(queryWrapper);
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }
        List<Integer> userIds = postList.stream().map(Post::getUserId).distinct().collect(Collectors.toList());
        List<User> userList = userService.listByIds(userIds);
        Map<Integer, User> userMap = new HashMap<>();
        if(CollUtil.isNotEmpty(userList)){
            userMap = userList.stream().collect(Collectors.toMap(User::getUid, Function.identity()));
        }

        List<Long> postIds = postList.stream().map(Post::getId).distinct().collect(Collectors.toList());
        // 帖子点赞量
        List<UpvoteVo> upvoteVos = upvoteService.postUpvoteCountByPostIds(postIds);
        Map<Long, Long> upvoteMap = new HashMap<>();
        if(CollUtil.isNotEmpty(upvoteVos)){
            upvoteMap = upvoteVos.stream().collect(Collectors.toMap(UpvoteVo::getPostId, UpvoteVo::getUpvoteCount));
        }

        Map<Integer, User> finalUserMap = userMap;
        Map<Long, Long> finalUpvoteMap = upvoteMap;
        return postList.stream().map(post -> {
            PostVo postVo = new PostVo();
            BeanUtils.copyProperties(post, postVo);
            User user = finalUserMap.get(post.getUserId());
            if(ObjectUtil.isNull(user)){
                postVo.setUser(null);
            }else {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                postVo.setUser(userVo);
            }

            Shop shopById = shopService.getById(post.getShopId());
            ShopVo shopVo = new ShopVo();
            BeanUtils.copyProperties(shopById,shopVo);
            postVo.setShop(shopVo);

            //关键字
            String keywords = post.getKeywords();
            if(ObjectUtil.isNotEmpty(keywords)){
                try {
                    List<String> keywordList = objectMapper.readValue(keywords, new TypeReference<List<String>>() {
                    });
                    postVo.setKeywordList(keywordList);
                } catch (JsonProcessingException e) {
                    throw new BusinessException("帖子关键字信息解析错误，帖子id：" + post.getId());
                }
            }
            //点赞量
            Long upvoteCount = finalUpvoteMap.get(post.getId());
            postVo.setUpvoteCount(ObjectUtil.isNotNull(upvoteCount) ? upvoteCount : 0);
            return postVo;
        }).collect(Collectors.toList());
    }

    @Override
    public PostVo detailById(Integer id) {
        if(ObjectUtil.isNull(id)){
            throw new BusinessException("参数错误");
        }
        Post post = getById(id);
        if(ObjectUtil.isNull(post)){
            throw new BusinessException("帖子详情不存在");
        }

        User loginUser = userService.getLoginUser();

        User user = userService.getById(post.getUserId());

        // 帖子点赞量
        List<UpvoteVo> upvoteVos = upvoteService.postUpvoteCountByPostIds(Collections.singletonList(post.getId()));
        Map<Long, Long> upvoteMap = new HashMap<>();
        if(CollUtil.isNotEmpty(upvoteVos)){
            upvoteMap = upvoteVos.stream().collect(Collectors.toMap(UpvoteVo::getPostId, UpvoteVo::getUpvoteCount));
        }

        PostVo postVo = new PostVo();
        BeanUtils.copyProperties(post, postVo);
        if(ObjectUtil.isNotNull(user)){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            postVo.setUser(userVo);
        }
        ShopVo shopById = shopService.getShopById3(post.getShopId());
        postVo.setShop(shopById);

        //关键字
        String keywords = post.getKeywords();
        if(ObjectUtil.isNotEmpty(keywords)){
            try {
                List<String> keywordList = objectMapper.readValue(keywords, new TypeReference<List<String>>() {
                });
                postVo.setKeywordList(keywordList);
            } catch (JsonProcessingException e) {
                throw new BusinessException("帖子关键字信息解析错误，帖子id：" + post.getId());
            }
        }
        //点赞量
        Long upvoteCount = upvoteMap.get(post.getId());
        postVo.setUpvoteCount(ObjectUtil.isNotNull(upvoteCount) ? upvoteCount : 0);


        Upvote upvote = upvoteService.getByPostIdAndUserId(postVo.getId(), loginUser.getUid());
        PostCollection postCollection = postCollectionService.getByPostIdAndUserId(postVo.getId(), loginUser.getUid());
        postVo.setIsCollected(ObjectUtil.isNotNull(postCollection));
        postVo.setIsUpvoted(ObjectUtil.isNotNull(upvote));

        return postVo;
    }

    @Override
    public List<PostVo> listVoByPostIdsAndUid(List<Long> postIdList, Integer uid) {
        List<Post> postList = listByIds(postIdList);
        if(CollUtil.isEmpty(postList)){
            return Collections.emptyList();
        }
        List<Integer> userIds = postList.stream().map(Post::getUserId).distinct().collect(Collectors.toList());
        List<User> userList = userService.listByIds(userIds);
        Map<Integer, User> userMap = new HashMap<>();
        if(CollUtil.isNotEmpty(userList)){
            userMap = userList.stream().collect(Collectors.toMap(User::getUid, Function.identity()));
        }
        List<Long> postIds = postList.stream().map(Post::getId).distinct().collect(Collectors.toList());
        // 帖子点赞量
        List<UpvoteVo> upvoteVos = upvoteService.postUpvoteCountByPostIds(postIds);
        Map<Long, Long> upvoteMap = new HashMap<>();
        if(CollUtil.isNotEmpty(upvoteVos)){
            upvoteMap = upvoteVos.stream().collect(Collectors.toMap(UpvoteVo::getPostId, UpvoteVo::getUpvoteCount));
        }

        Map<Integer, User> finalUserMap = userMap;
        Map<Long, Long> finalUpvoteMap = upvoteMap;
        return postList.stream().map(post -> {
            PostVo postVo = new PostVo();
            BeanUtils.copyProperties(post, postVo);
            User user = finalUserMap.get(post.getUserId());
            if(ObjectUtil.isNull(user)){
                postVo.setUser(null);
            }else {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                postVo.setUser(userVo);
            }

            ShopVo shopById = shopService.getShopByIdAndUid(post.getShopId());
            postVo.setShop(shopById);

            //关键字
            String keywords = post.getKeywords();
            if(ObjectUtil.isNotEmpty(keywords)){
                try {
                    List<String> keywordList = objectMapper.readValue(keywords, new TypeReference<List<String>>() {
                    });
                    postVo.setKeywordList(keywordList);
                } catch (JsonProcessingException e) {
                    throw new BusinessException("帖子关键字信息解析错误，帖子id：" + post.getId());
                }
            }
            //点赞量
            Long upvoteCount = finalUpvoteMap.get(post.getId());
            postVo.setUpvoteCount(ObjectUtil.isNotNull(upvoteCount) ? upvoteCount : 0);
            return postVo;
        }).collect(Collectors.toList());
    }
}




